<template>
    <div class="full-size-scrollbar">
        <div v-if="comments && comments.length > 0">
        <div v-for="(comment, commentIndex) in comments" :key="commentIndex" style="margin-top: 5px">
            <div class="avatar-with-username">
                <el-avatar :src="comment.avatar" :size="40" @click="avaClick(comment.user_id)"/>
                <div class="username-container">
                    <p style="font-size: 15px">{{ comment.username }}</p>
                </div>
            </div>
            <div class="comment-text">
                <p style="font-size: 15px">{{ comment.text }}</p>
                <div style = "margin-top: 5px;display:flex;"  >
                    <!-- 爱心图标 -->
                    <label class="container" style = "margin-left: 300px ;">
                        <input type="checkbox" v-model="comment.is_like" @change="toggleLike(commentIndex,0, comment.comment_id, 1 )" />
                        <div class="checkmark">
                            <svg viewBox="0 0 256 256">
                                <path class="like" d="M224.6,51.9a59.5,59.5,0,0,0-43-19.9,60.5,60.5,0,0,0-44,17.6L128,59.1l-7.5-7.4C97.2,28.3,59.2,26.3,35.9,47.4a59.9,59.9,0,0,0-2.3,87l83.1,83.1a15.9,15.9,0,0,0,22.6,0l81-81C243.7,113.2,245.6,75.2,224.6,51.9Z" stroke-width="18px" stroke="#000000" fill="none"></path>
                            </svg>
                        </div>
                    </label>
                    <p  style = " font-size: 17px; margin-left: 10px ; margin-right: 5px; margin-top : -5px;">{{ comment.like_count }}</p>
                    <el-icon :size="22" style = "margin-left: 10px ; margin-right: 5px ; margin-top : -5px">
                        <ChatDotRound />
                    </el-icon>
                    <span style="font-size: 15px; margin-top : -5px; " class="reply-btn" @click="toggleReplies(commentIndex, comment.comment_id, comment.comment_id, comment.user_id, comment.username, 2)">回复</span>
                    <el-icon class="deletecomment" v-if = "user_ID===comment.user_id" :size="22" style = "margin-left: 13px ; margin-right: 5px ; margin-top : -6px" @click="DeleteComment(commentIndex, comment.comment_id,false,null, comment.replies?.length ?? 0)">
                        <Delete />
                    </el-icon>
                </div>
            </div>
            <div v-if="comment.replies && comment.replies.length > 0">
                <div v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="reply">
                    <div class="avatar-with-username">
                        <el-avatar :src="reply.avatar" :size="30" @click="avaClick(reply.user_id)"/>
                        <div class="username-container">
                            <p class="username">{{ reply.username }}</p>
                        </div>
                    </div>
                    <div class="reply-text">
                        <p>{{ '回复了' + reply.reply_username + ' : ' + reply.text }}</p>
                        <div style = "display:flex; margin-top: 10px;margin-left: 290px ;" >
                            <label class="container">
                                <input type="checkbox" v-model="reply.is_like" @change="toggleLike(commentIndex, replyIndex, reply.comment_id , 2)"  />
                                <div class="checkmark">
                                    <svg viewBox="0 0 256 256">
                                        <path class="like" d="M224.6,51.9a59.5,59.5,0,0,0-43-19.9,60.5,60.5,0,0,0-44,17.6L128,59.1l-7.5-7.4C97.2,28.3,59.2,26.3,35.9,47.4a59.9,59.9,0,0,0-2.3,87l83.1,83.1a15.9,15.9,0,0,0,22.6,0l81-81C243.7,113.2,245.6,75.2,224.6,51.9Z" stroke-width="18px" stroke="#000000" fill="none"></path>
                                    </svg>
                                </div>
                            </label>
                            <p style = "margin-left: 10px ; margin-right: 5px ; margin-top: -3px">{{ reply.like_count }}</p>
                            <el-icon :size="22" style = "margin-left: 10px ; margin-right: 5px;margin-top: -5px">
                                <ChatDotRound />
                            </el-icon>
                            <span class="reply-btn1" @click="toggleReplies(commentIndex, comment.comment_id, reply.comment_id, reply.user_id, reply.username, 3)">回复</span>
                            <el-icon  v-if = "user_ID===reply.user_id" :size="22" style = "margin-left: 10px ; margin-right: 5px;margin-top: -6px" @click="DeleteComment(commentIndex, reply.comment_id,true,replyIndex)">
                                <Delete />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
        <div v-else>
            <p>暂无评论</p>
        </div>
    </div>
</template>

<script setup>
import {ref, defineEmits,defineProps, onMounted,watch} from 'vue';
import axios from 'axios';
import router from "@/router";
import {ElMessage} from "element-plus";
const props = defineProps({
    isAdopt : {
         type: Boolean,
         default: false
    },
    comments : {
         type: Array,
         default: () => []
    },
    textcount : {
        type: Number,
        default: 0
    }
})
// 定义向父组件抛出的事件
const emit = defineEmits(['toggle-replies']);
const user_ID = ref(0);
const comments = ref(props.comments);
const userData = JSON.parse(sessionStorage.getItem('token'));
axios.defaults.headers.common['Authorization'] = `${userData.token}`;
user_ID.value = userData.userID;
const DeleteComment = async (commentIndex, commentId, isReply = false, replyIndex = null,repliesLen = 0) => {
        const response = await axios.post('http://localhost:8080/comment/delete', { commentId });
        if (response.status === 200) {
            const textcountLast = ref(props.textcount - 1);
            if (isReply && replyIndex !== null) {
                // 删除子评论
                comments.value[commentIndex].replies.splice(replyIndex, 1);
            } else {
                // 删除评论
                comments.value.splice(commentIndex, 1);
                textcountLast.value = textcountLast.value - repliesLen;
            }
            console.log(props.textcount);
            console.log(textcountLast.value);
            // 更新 textcount
            emit('updateTextCounter', textcountLast.value);
            console.log("删除成功");
            ElMessage({
                message: '删除成功',
                type: 'error',
                style: 'font-size:25px;font-weight:bold;',
                offset: 55,
                grouping: true
            });
            // 重新获取评论列表
            const PassageIDchuchu = props.isAdopt ? 'AdoptPassageID' : 'PassageID';
            const userData1 = JSON.parse(sessionStorage.getItem(PassageIDchuchu));
            const response1 = await axios.get('http://localhost:8080/comment/list/' + userData1.PassageID, {});
            if (response1.status === 200) {
                comments.value = response1.data.data;
                console.log(comments.value);
            }
        } else {
            console.error('删除失败:', response.data.message);
        }
};
// 定义toggleReplies方法，通过emit触发事件传递给父组件
const toggleReplies = (commentIndex, parentID, commentId, replyUserID, username, type) => {
    emit('toggle-replies', commentIndex, parentID, commentId, replyUserID, username, type);
};

// 点赞或取消点赞
const toggleLike = async (commentIndex, replyIndex,commentId,type) => {
    const isLiked = ref(false);
    if(type == 1)
        isLiked.value = comments.value[commentIndex].is_like;
    else
        isLiked.value = comments.value[commentIndex].replies[replyIndex].is_like;
    try {
        if (isLiked.value) {
            const response = await axios.post('http://localhost:8080/likes/comment/add', { commentId });
            console.log(response.data);
            if(response.status == 200 ){
                if(type == 1){
                    comments.value[commentIndex].is_like = true;
                    comments.value[commentIndex].like_count++;
                }
                else{
                    comments.value[commentIndex].replies[replyIndex].is_like = true;
                    comments.value[commentIndex].replies[replyIndex].like_count++;
                }
                console.log("点赞成功");
            }
            else{
                console.error('操作失败:', response.data.message);
                if(type == 1){
                    comments.value[commentIndex].is_like = false;
                    comments.value[commentIndex].like_count--;
                }
                else{
                    comments.value[commentIndex].replies[replyIndex].is_like = false;
                    comments.value[commentIndex].replies[replyIndex].like_count--;
                }
                alert('操作失败');
            }
        } else {
            // 点赞
            const response =  await axios.post('http://localhost:8080/likes/comment/undo', { commentId});
            if(response.status==200){
                if(type == 1) {
                    comments.value[commentIndex].like_count--;
                    comments.value[commentIndex].is_like = false;
                }
                else{
                    comments.value[commentIndex].replies[replyIndex].like_count--;
                    comments.value[commentIndex].replies[replyIndex].is_like = false;
                }
                console.log("取消点赞成功")
            }
            else{
                console.error('操作失败:', response.data.message);
                if(type == 1)
                    comments.value[commentIndex].is_like = true;
                else
                    comments.value[commentIndex].replies[replyIndex].is_like = true;
                alert('操作失败');
            }
        }
    } catch (error) {
        console.error('点赞/取消点赞失败：', error);
        if(type == 1)
            comments.value[commentIndex].is_like = !comments.value[commentIndex].is_like;
        else
            comments.value[commentIndex].replies[replyIndex].is_like = !comments.value[commentIndex].replies[replyIndex].is_like;
        alert('点赞/取消点赞失败：');
    }
};

const avaClick = (user_id) => {
    const data = { id:user_id };
    console.log(user_id);
    sessionStorage.setItem('userData', JSON.stringify(data));
    router.push({
        path:'/UserPage',
        query: {
            id: user_id,
        }
    })
    console.log("点击了头像");
}

watch(() => props.comments, (newComments) => {
    comments.value = newComments;
}, { immediate: true });

onMounted(async () => {
    console.log("comment list mounted!");
    console.log(props.comments);
})
</script>

<style scoped>
.full-size-scrollbar {
    display: flex;
    flex-direction: column;
    margin-right: 10px;
}

/* 头像与用户名组合容器样式 */
.avatar-with-username {
    display: flex;
    align-items: center;
}
.el-avatar{
    cursor: pointer;
}
/* 用户名容器样式 */
.username-container {
    margin-left: 5px;
    font-weight: bold;
}

/* 评论文字样式 */
.comment-text {
    text-align: left;
    margin-left: 45px;
    margin-right: 5px;
    margin-top: -10px;
}

/* 回复按钮样式 */
.reply-btn {
    cursor: pointer;
    color: #666;
}

/* 回复（被评论）的容器样式，相对评论缩进显示 */
.reply {
    margin-left: 40px;
    border-left: 2px solid #ccc;
    padding-left: 10px;
    display: flex;
    margin-top: -20px;
    flex-direction: column;
}

/* 回复文字样式 */
.reply-text {
    margin-top: 5px;
    text-align: left;
    margin-left: 5px;
    margin-right: 10px;
}
/* 回复按钮样式 */
.reply-btn1 {
    cursor: pointer;
    color: #666;
    margin-top: -3px;
}
.deletecomment{
    cursor: pointer;
    color: #666;
}
/* 爱心图标样式 */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.container {
    display: block;
    position: relative;
    cursor: pointer;
    user-select: none;
    transition: 100ms;
    margin-top: -5px;
}

.checkmark {
    top: 0;
    left: 0;
    height: 22px;
    width: 22px;
    transition: 100ms;
    animation: dislike_effect 500ms ease;
    margin-left: 10px;
}

.container input:checked ~ .checkmark path {
    fill: #FFD466;
    stroke-width: 0;
}

.container input:checked ~ .checkmark {
    animation: like_effect 400ms ease;
}

.container:hover {
    transform: scale(1.2);
}

.container:hover .like {
    stroke: #FFD466;
}

@keyframes like_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}

@keyframes dislike_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}
</style>
